<template>
  <view class="container">
    <!-- 顶部地址栏 - 修改为可点击 -->
    <view class="location-bar" :style="{ paddingTop: statusBarHeight }">
      <view class="location" @click="goToMapPage">
        <uni-icons type="location" size="20" color="#FF8C42"></uni-icons>
        <text class="location-text">{{ currentAddress || '当前位置' }}</text>
        <view class="location-arrow">
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <!-- 搜索和扫码区域 -->
      <view class="search-container">
        <view class="search-box">
          <uni-search-bar
            v-model="searchKeyword"
            placeholder="搜索商品..."
            radius="100"
            cancelButton="none"
            @confirm="search"
            backgroundColor="#F8F8F8"
            @clear="clearSearch"
            clearButton="auto"
          ></uni-search-bar>
        </view>
        <view class="scan-btn" @click="scanCode">
          <uni-icons type="scan" size="24" color="#FF8C42"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 促销横幅 -->
    <view class="promo-banner">
      <swiper class="banner-swiper" indicator-dots autoplay circular indicator-color="rgba(255,255,255,0.4)" indicator-active-color="#fff">
        <swiper-item>
          <view class="banner-item banner-1">
            <view class="banner-content">
              <view class="banner-text">
                <text class="banner-title">限时特惠</text>
                <text class="banner-subtitle">精选零食买二送一</text>
                <view class="banner-btn" @click="goToSpecialOffer">立即抢购</view>
              </view>
              <view class="banner-image">
                <image src="/static/index-1.png" mode="aspectFit" class="nuts-image"></image>
              </view>
            </view>
          </view>
        </swiper-item>
        <swiper-item>
          <view class="banner-item banner-2">
            <view class="banner-content">
              <text class="banner-title">新品上市</text>
              <text class="banner-subtitle">尝鲜价低至5折</text>
              <view class="banner-btn">查看详情</view>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>
    
    <!-- 分类过滤 -->
    <view class="filter-bar">
      <scroll-view scroll-x class="category-scroll" show-scrollbar="false">
        <view 
          class="filter-item" 
          :class="{ active: activeCategory === 'all' }"
          @click="changeCategory('all')"
        >
          <image src="/static/all.png" mode="aspectFit" class="category-icon"></image>
          <text>全部</text>
        </view>
        <view 
          class="filter-item" 
          :class="{ active: activeCategory === 'drink' }"
          @click="changeCategory('drink')"
        >
          <image src="/static/cup.png" mode="aspectFit" class="category-icon"></image>
          <text>饮料</text>
        </view>
        <view 
          class="filter-item" 
          :class="{ active: activeCategory === 'snack' }"
          @click="changeCategory('snack')"
        >
          <uni-icons type="shop" size="18" :color="activeCategory === 'snack' ? '#fff' : '#666'"></uni-icons>
          <text>零食</text>
        </view>
        <view 
          class="filter-item" 
          :class="{ active: activeCategory === 'fruit' }"
          @click="changeCategory('fruit')"
        >
          <uni-icons type="star" size="18" :color="activeCategory === 'fruit' ? '#fff' : '#666'"></uni-icons>
          <text>水果</text>
        </view>
        <view 
          class="filter-item" 
          :class="{ active: activeCategory === 'fast' }"
          @click="changeCategory('fast')"
        >
          <uni-icons type="fire" size="18" :color="activeCategory === 'fast' ? '#fff' : '#666'"></uni-icons>
          <text>速食</text>
        </view>
      </scroll-view>
      
      <view class="sort-box" @click="toggleSortMenu">
        <text>{{ sortDisplayText }}</text>
        <uni-icons type="bars" size="18" color="#666"></uni-icons>
      </view>
    </view>
    
    <!-- 排序菜单 -->
    <uni-popup ref="sortPopup" type="top" :custom-style="popupStyle">
      <view class="sort-menu">
        <view class="sort-item" @click="sortBy('default')">
          <text>默认排序</text>
          <uni-icons v-if="sortType === 'default'" type="checkmarkempty" size="18" color="#FF8C42"></uni-icons>
        </view>
        <view class="sort-item" @click="sortBy('price_asc')">
          <text>价格从低到高</text>
          <uni-icons v-if="sortType === 'price_asc'" type="checkmarkempty" size="18" color="#FF8C42"></uni-icons>
        </view>
        <view class="sort-item" @click="sortBy('price_desc')">
          <text>价格从高到低</text>
          <uni-icons v-if="sortType === 'price_desc'" type="checkmarkempty" size="18" color="#FF8C42"></uni-icons>
        </view>
        <view class="sort-item" @click="sortBy('sales_desc')">
          <text>销量从高到低</text>
          <uni-icons v-if="sortType === 'sales_desc'" type="checkmarkempty" size="18" color="#FF8C42"></uni-icons>
        </view>
        <view class="sort-item" @click="sortBy('sales_asc')">
          <text>销量从低到高</text>
          <uni-icons v-if="sortType === 'sales_asc'" type="checkmarkempty" size="18" color="#FF8C42"></uni-icons>
        </view>
      </view>
    </uni-popup>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-load-more status="loading" :contentText="loadingText"></uni-load-more>
    </view>
    
    <!-- 商品瀑布流 -->
    <view v-else class="product-grid">
      <view 
        class="product-item" 
        v-for="(item, index) in filteredProducts" 
        :key="item.id"
        @click="goToDetail(item.id)"
      >
        <view class="product-tag" v-if="item.status === 0">已下架</view>
        <view class="product-tag" v-else-if="item.totalStock <= item.safeStock" style="background-color: #FF9F1C;">库存紧张</view>
          <image 
            class="product-image" 
            :src="imageFullUrl(item.mainImageUrl)" 
            mode="aspectFill"
            @error="handleImageError($event, index)"
          ></image>
        <view class="product-info">
          <text class="product-name">{{ item.name }}</text>
          <text class="product-desc">{{ item.description }}</text>
          <view class="product-bottom">
            <view class="price-box">
              <text class="product-price">¥{{ parseFloat(item.price).toFixed(2) }}</text>
            </view>
            <!-- <view class="product-sales">库存: {{ item.totalStock }}</view> -->
          </view>
          <view class="button-group">
              <view class="buy-btn purchase" @click.stop="purchaseNow(item)">
                <uni-icons type="shopping-cart-filled" size="16" color="#fff"></uni-icons>
                <text>立即购买</text>
              </view>
              <view class="buy-btn cart" @click.stop="addToCart(item)">
                <uni-icons type="cart" size="16" color="#fff"></uni-icons>
                <text>加入购物车</text>
              </view>
            </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view v-if="!loading && filteredProducts.length === 0" class="empty-state">
      <image src="/static/placeholder.png" mode="aspectFit" class="empty-image"></image>
      <text class="empty-text">暂无商品</text>
    </view>
    
    <!-- 登录弹窗 -->
    <login-popup ref="loginPopup"></login-popup>
       
    <!-- 用户类型管理 -->
    <user-type-manager></user-type-manager>
    
    <!-- 底部导航栏 -->
    <tab-bar :active="0"></tab-bar>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import TabBar from '@/components/tab-bar.vue';
import LoginPopup from '@/components/login-popup.vue';
import UserTypeManager from '@/components/user-type-manager.vue';
import http from '@/utils/http/http.js';
import { useUserStore } from '@/store/user';
import { useProductStore } from '@/store/product.js';
import { useCartStore } from '@/store/cart.js';
import { getImageUrl } from '@/config/env';
import { onShow } from '@dcloudio/uni-app';

// 在setup函数中添加商品状态管理
const productStore = useProductStore();
// 用户状态
const userStore = useUserStore();
// 购物车状态
const cartStore = useCartStore();

// 状态栏高度
const statusBarHeight = ref('0px');

// 组件引用
const loginPopup = ref(null);
const sortPopup = ref(null);

// 加载状态
const loading = ref(false);
const loadingText = {
  contentdown: "正在加载...",
  contentrefresh: "加载中...",
  contentnomore: "没有更多数据了"
};

// 当前地址状态
const currentAddress = ref('');

// 商品数据
const products = ref([]);

// 搜索相关状态
const searchKeyword = ref('');
const isSearchMode = ref(false);

// 排序和筛选状态
const activeCategory = ref('all');
const sortType = ref('default');

// 分类映射
const categoryMap = {
  1: 'fruit',   // 水果
  2: 'snack',   // 零食
  3: 'drink',   // 饮料
  4: 'fast'     // 速食
};

// 排序显示文本
const sortDisplayText = computed(() => {
  switch (sortType.value) {
    case 'default': return '默认排序';
    case 'price_asc': return '价格↑';
    case 'price_desc': return '价格↓';
    case 'sales_asc': return '库存↑';
    case 'sales_desc': return '库存↓';
    default: return '排序';
  }
});

// 根据分类和排序过滤商品
const filteredProducts = computed(() => {
  let result = [...products.value];
  
  // 分类过滤 - 使用 categoryId
  if (activeCategory.value !== 'all') {
    result = result.filter(item => categoryMap[item.categoryId] === activeCategory.value);
  }
  
  // 排序 - 使用 totalStock
  switch (sortType.value) {
    case 'price_asc':
      result.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
      break;
    case 'price_desc':
      result.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
      break;
    case 'sales_asc':
      result.sort((a, b) => a.totalStock - b.totalStock);
      break;
    case 'sales_desc':
      result.sort((a, b) => b.totalStock - a.totalStock);
      break;
    default:
      // 默认排序，按ID排序
      result.sort((a, b) => a.id - b.id);
      break;
  }
  
  return result;
});

// 跳转到特惠页面
const goToSpecialOffer = () => {
  // 设置分类为零食并显示相关商品
  activeCategory.value = 'snack';
  uni.showToast({
    title: '已为您筛选零食特惠商品',
    icon: 'success'
  });
};

// 立即购买 - 更新为不需要登录
const purchaseNow = async (product) => {
  try {
    // 显示加载中
    uni.showLoading({
      title: '处理中...',
      mask: true
    });
    
    // 模拟处理时间
    setTimeout(() => {
      // 隐藏加载
      uni.hideLoading();
      
      // 显示购买成功提示
      uni.showToast({
        title: '购买成功',
        icon: 'success',
        duration: 2000
      });
      
      // 可以在这里添加其他逻辑，比如跳转到订单页面
      // setTimeout(() => {
      //   uni.navigateTo({
      //     url: '/pages/orders/success?productName=' + encodeURIComponent(product.name)
      //   });
      // }, 1500);
    }, 800);
  } catch (error) {
    console.error('购买失败:', error);
    uni.hideLoading();
    uni.showToast({ 
      title: '购买失败，请重试', 
      icon: 'none' 
    });
  }
};

// 弹出层样式配置
const popupStyle = {
  top: '80rpx', // 调整距离顶部的间距
  position: 'absolute',
  width: '100%'
};

// 获取当前位置
const getCurrentLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      console.log('获取位置成功:', res);
      // 使用逆地理编码获取地址
      uni.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=YOUR_KEY`,
        success: (addressRes) => {
          if (addressRes.data && addressRes.data.result) {
            const address = addressRes.data.result.address;
            currentAddress.value = address;
          }
        },
        fail: () => {
          currentAddress.value = '未知位置';
        }
      });
    },
    fail: (err) => {
      console.error('获取位置失败:', err);
      currentAddress.value = '未知位置';
    }
  });
};

// 跳转到地图页面
const goToMapPage = () => {
  uni.navigateTo({
    url: '/pages/map/index'
  });
};

// 切换分类
const changeCategory = (category) => {
  activeCategory.value = category;
};

// 切换排序菜单
const toggleSortMenu = () => {
  sortPopup.value.open();
};

// 排序
const sortBy = (type) => {
  sortType.value = type;
  sortPopup.value.close();
};

// 搜索商品
const search = async (e) => {
  console.log('搜索关键词:', e.value);
  const keyword = e.value.trim();
  
  // 空值校验
  if (!keyword) {
    uni.showToast({
      title: '请输入搜索关键词',
      icon: 'none'
    });
    return;
  }
  
  isSearchMode.value = true;
  
  try {
    loading.value = true;
    
    // 调用搜索接口
    const response = await http.get('/api/products/search', {
      params: {
        keyword: keyword,
        limit: 20 // 默认显示20条
      }
    });

    if (response.code === 200 && response.data) {
      // 更新商品列表
      products.value = response.data;
      
      uni.showToast({
        title: `找到${response.data.length}个商品`,
        icon: 'none'
      });
    } else {
      uni.showToast({
        title: response.message || '搜索失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('搜索请求失败:', error);
    uni.showToast({
      title: '搜索失败，请检查网络',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = '';
  isSearchMode.value = false;
  // 重新获取所有商品
  fetchProducts();
};

// 扫描二维码
const scanCode = () => {
  uni.scanCode({
    success: (res) => {
      console.log('扫码结果:', res);
      // 处理扫码结果
      if (res.result) {
        uni.showToast({
          title: '扫码成功',
          icon: 'success'
        });
        
        // 根据扫码结果类型处理
        try {
          // 尝试解析为JSON
          const data = JSON.parse(res.result);
          if (data.type === 'product') {
            // 商品二维码
            goToDetail(data.id);
          } else if (data.type === 'shelf') {
            // 货架二维码
            uni.navigateTo({
              url: `/pages/map/index?shelfId=${data.id}`
            });
          } else {
            // 其他类型
            uni.showModal({
              title: '扫码结果',
              content: res.result,
              showCancel: false
            });
          }
        } catch (e) {
          // 不是JSON格式，可能是URL或其他文本
          if (res.result.startsWith('http')) {
            // 是URL，打开网页
            uni.navigateTo({
              url: `/pages/webview/index?url=${encodeURIComponent(res.result)}`
            });
          } else {
            // 其他文本
            uni.showModal({
              title: '扫码结果',
              content: res.result,
              showCancel: false
            });
          }
        }
      }
    },
    fail: (err) => {
      console.error('扫码失败:', err);
      uni.showToast({
        title: '扫码失败',
        icon: 'none'
      });
    }
  });
};


// 修改跳转到商品详情页的函数
const goToDetail = (id) => {
 // 增加ID校验
   if (!id || typeof id !== 'number') {
     uni.showToast({ title: '商品ID异常', icon: 'none' });
     return;
   }
 
   // 存储到状态管理时进行深拷贝
   const product = products.value.find(item => item.id === id);
   if (product) {
     productStore.setCurrentProduct(JSON.parse(JSON.stringify(product)));
   }
  //console.log("id",id);
   // 添加路由参数校验
   uni.navigateTo({
	  
     url: `/pages/product/detail?id=${id}&t=${Date.now()}` // 添加时间戳避免缓存
   });
};

// 加入购物车
const addToCart = async (product) => {
  try {
    // 使用购物车 store 的 addToCart 方法
    const result = await cartStore.addToCart(product, 1);
    
    // 如果添加成功，可以在这里做一些额外的操作
    if (result) {
      console.log('商品已成功添加到购物车');
    }
  } catch (error) {
    console.error('添加购物车失败:', error);
    uni.showToast({
      title: '添加购物车失败，请重试',
      icon: 'none'
    });
  }
};

// 处理图片加载错误
const handleImageError = (e, index) => {
  console.error('图片加载失败:', e, '商品索引:', index);
  // 设置默认图片
  if (products.value && products.value[index]) {
    products.value[index].mainImageUrl = '/static/placeholder.png';
  }
};

// 获取商品列表
const fetchProducts = async () => {
  loading.value = true;
  try {
    const response = await http.get('/api/products/all');
    console.log('获取商品列表成功:', response);
    
    if (response.code === 200 && response.data) {
      products.value = response.data;
      console.log('商品数据:', products.value);
      
      // 保存商品数据到状态管理
      productStore.setProducts(products.value);
      
      // 调试分类信息
      products.value.forEach(product => {
        console.log(`商品 ${product.name} 的分类ID: ${product.categoryId}, 映射为: ${categoryMap[product.categoryId]}`);
      });
    } else {
      uni.showToast({
        title: response.message || '获取商品列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    uni.showToast({
      title: '获取商品列表失败，请检查网络',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 生成完整的图片 URL - 使用统一的工具函数
const imageFullUrl = getImageUrl;

// 生命周期钩子
onMounted(() => {
  // 获取系统信息
  let systemInfo = null;
  try {
    systemInfo = uni.getSystemInfoSync();
  } catch (e) {
    console.error("Failed to get system info:", e);
  }
  if (systemInfo) {
    statusBarHeight.value = `${systemInfo.statusBarHeight || 20}px`; // 默认20px
  } else {
    statusBarHeight.value = '20px'; // 默认值
  }
  
  // 初始化用户状态
  userStore.initUserState();
  
  // 获取当前位置
  getCurrentLocation();
  
  // 首次进入APP时显示登录弹窗
  const hasShown = uni.getStorageSync('hasShownLoginPopup');
  console.log('本地存储 hasShownLoginPopup:', hasShown);
  console.log('检查是否需要显示登录弹窗:', !userStore.isLoggedIn, !hasShown);
  
  if (!userStore.isLoggedIn && !hasShown) {
    console.log('准备显示登录弹窗');
    // 确保组件已经挂载
    setTimeout(() => {
      if (loginPopup.value) {
        console.log('打开登录弹窗');
        loginPopup.value.open();
      } else {
        console.error('登录弹窗组件未找到');
      }
    }, 500);
  }
  
  // 获取商品列表
  fetchProducts();
  
  // 获取购物车数量
  cartStore.fetchCartList();
  cartStore.getCartCount();
});

// 每次显示页面时刷新数据
onShow(() => {
  console.log('首页显示，重新初始化用户状态');
  // 重新初始化用户状态，确保从其他页面跳转回来时能正确获取登录状态
  userStore.initUserState();
  // 刷新购物车数据
  cartStore.fetchCartList();
  cartStore.getCartCount();
});
</script>

<style>
.container {
  padding-bottom: 100rpx;
  background-color: #FFF9F2;
}

/* 顶部地址栏 */
.location-bar {
  padding: 20rpx;
  padding-top: 0;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border-bottom: 1rpx solid #FFE6CC;
}

.location {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
  background-color: #FFF9F2;
  padding: 12rpx 20rpx;
  border-radius: 30rpx;
  transition: all 0.3s ease;
}

.location:active {
  background-color: #FFE6CC;
}

.location-text {
  flex: 1;
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.location-arrow {
  margin-left: 10rpx;
}

/* 搜索和扫码区域 */
.search-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.search-box {
  flex: 1;
}

.scan-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #FFF9F2;
  border-radius: 50%;
  margin-left: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.scan-btn:active {
  transform: scale(0.95);
  background-color: #FFE6CC;
}

/* 促销横幅 */
.promo-banner {
  margin: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.banner-swiper {
  height: 200rpx;
}

.banner-item {
  height: 100%;
  display: flex;
  align-items: center;
  padding: 0 40rpx;
}

.banner-1 {
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
}

.banner-2 {
  background: linear-gradient(to right, #F9C784, #FCAF58);
}

.banner-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  color: white;
}

.banner-text {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.banner-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  display: block;
}

.banner-subtitle {
  font-size: 28rpx;
  margin-bottom: 20rpx;
  display: block;
  opacity: 0.9;
}

.banner-btn {
  display: inline-block;
  padding: 10rpx 30rpx;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 30rpx;
  font-size: 24rpx;
  transition: all 0.3s ease;
}

.banner-btn:active {
  background-color: rgba(255, 255, 255, 0.5);
  transform: scale(0.95);
}

.banner-image {
  width: 120rpx;
  height: 120rpx;
  margin-left: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nuts-image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
  background-color: rgba(255, 255, 255, 0.1);
}

/* 分类过滤 */
.filter-bar {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  gap: 20rpx;
}

.category-scroll {
  flex: 1;
  white-space: nowrap;
  max-width: 75%;
}

.filter-item {
  display: inline-flex;
  align-items: center;
  margin-right: 30rpx;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  border: 1rpx solid #FFE6CC;
  background-color: #fff;
  transition: all 0.3s ease;
}

/* 按钮组 - 美化版 */
.button-group {
  display: flex;
  gap: 12rpx;
  margin-top: 16rpx;
}

/* 通用按钮样式 - 美化版 */
.buy-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 0;
  border-radius: 40rpx;
  font-size: 22rpx;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

/* 购买按钮 - 美化版 */
.buy-btn.purchase {
  background: linear-gradient(135deg, #F9C784, #F57C00);
  color: white;
}

/* 购物车按钮 - 美化版 */
.buy-btn.cart {
  background: linear-gradient(135deg, #FF9800, #F57C00);
  color: white;
}

/* 按钮图标与文字间距 */
.buy-btn uni-icons {
  margin-right: 8rpx;
}

/* 点击效果 - 美化版 */
.buy-btn:active {
  opacity: 0.85;
  transform: scale(0.97);
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.category-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.filter-item text {
  font-size: 26rpx;
  color: #333;
}

.filter-item.active {
  background-color: #FF8C42;
  border-color: #FF8C42;
}

.filter-item.active text {
  color: #fff;
}

.sort-box {
  flex-shrink: 0;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  border: 1rpx solid #FFE6CC;
  background-color: #fff;
  min-width: 120rpx;
}

.sort-box text {
  margin-right: 10rpx;
  font-size: 26rpx;
  color: #333;
}

/* 排序菜单 */
.sort-menu {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 0 0 16rpx 16rpx;
  margin-top: 80rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.sort-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #FFE6CC;
}

.sort-item:last-child {
  border-bottom: none;
  padding: 30rpx 20rpx;
}

/* 加载状态 */
.loading-container {
  padding: 40rpx 0;
  display: flex;
  justify-content: center;
}

/* 商品瀑布流 */
.product-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 10rpx;
}

.product-item {
  width: calc(50% - 20rpx);
  margin: 10rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: relative;
  transition: transform 0.3s ease;
}

.product-item:active {
  transform: scale(0.98);
}

.product-tag {
  position: absolute;
  top: 16rpx;
  left: 0;
  background-color: #FF8C42;
  color: white;
  font-size: 22rpx;
  padding: 6rpx 16rpx;
  border-radius: 0 20rpx 20rpx 0;
  z-index: 1;
}

.product-image {
  width: 100%;
  height: 300rpx;
  background-color: #f5f5f5;
}

.product-info {
  padding: 20rpx;
}

.product-name {
  font-size: 30rpx;
  color: #333;
  font-weight: bold;
  display: block;
  margin-bottom: 8rpx;
}

.product-desc {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  height: 64rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.price-box {
  display: flex;
  align-items: baseline;
}

.product-price {
  font-size: 34rpx;
  color: #FF8C42;
  font-weight: bold;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  margin-left: 10rpx;
}

.product-sales {
  font-size: 22rpx;
  color: #999;
}

.buy-now {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #FF8C42;
  color: white;
  padding: 12rpx 0;
  border-radius: 30rpx;
  font-size: 26rpx;
  transition: background-color 0.3s ease;
}

.buy-now:active {
  background-color: #FF9F1C;
}

.buy-now text {
  margin-left: 8rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

@media screen and (max-width: 375px) {
  .product-item {
    width: calc(50% - 20rpx);
  }
}
</style>